import os
from sqlmodel import SQLModel, create_engine, Session
from typing import Generator
import logging

logger = logging.getLogger(__name__)

# 数据库配置
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./jpy_rates.db")

# 创建引擎
engine = create_engine(
    DATABASE_URL,
    connect_args={"check_same_thread": False} if "sqlite" in DATABASE_URL else {},
    echo=False  # 生产环境关闭SQL日志
)


def create_db_and_tables():
    """创建数据库和表"""
    try:
        SQLModel.metadata.create_all(engine)
        logger.info("数据库表创建成功")
    except Exception as e:
        logger.error(f"创建数据库表失败: {e}")
        raise


def get_session() -> Generator[Session, None, None]:
    """获取数据库会话"""
    with Session(engine) as session:
        try:
            yield session
        except Exception as e:
            logger.error(f"数据库会话错误: {e}")
            session.rollback()
            raise
        finally:
            session.close()


def check_database_connection() -> bool:
    """检查数据库连接"""
    try:
        with Session(engine) as session:
            session.exec("SELECT 1")
            return True
    except Exception as e:
        logger.error(f"数据库连接检查失败: {e}")
        return False
